<template>
  <div id="main">
    <div v-if="cordova && cordova.deviceready"></div>
    <view-box>

      <x-header slot="header" :left-options="{showBack: false}">投票列表
        <a slot="right" @click="onAdd" v-if="submitVoteButtonVisibility">发布投票</a>
        <x-icon @click="onDrawer" slot="overwrite-left" type="navicon" size="35" style="fill:#fff;position:relative;top:-8px;left:-3px;"></x-icon>
      </x-header>
      <scroller ref="scroller" lock-x scrollbar-y @on-scroll="onScroll" @on-scroll-bottom="onScrollBottom">
        <div>
          <div class="refresh-spinner">
            <spinner type="lines" size="46px"></spinner>
          </div>
          <card v-for="item in voteList" :key="item.id" class="vote-item-card" @click.native="go2Content(item.id)">
            <div slot="content" class="card-padding">
              <vote-flag :deadline="item.deadline" />
              <avatar :account="item.creatorAccount" :username="item.creatorUsername" :datetime="item.updatedAt" />
              <p class="vote-topic">{{ item.topic }}</p>
            </div>
          </card>
        </div>
      </scroller>

    </view-box>

  </div>

</template>

<style lang="less">
#main {
  height: 100%;
  background-color: #fbf9fe;
  .vux-header {
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1000;
  }
  .refresh-spinner {
    text-align: center;
  }
  .vote-item-card {
    padding: 1rem;
    .vote-topic {
      margin-top: 0.5rem;
    }
  }
}
</style>

<script>
import Vue from "vue";
import { mapGetters, mapActions, mapState, mapMutations } from "vuex";
import {
  Scroller,
  XHeader,
  ViewBox,
  Card,
  Sticky,
  Confirm,
  Spinner,
  TransferDomDirective as TransferDom,
  ConfirmPlugin
} from "vux";
import Avatar from "../components/Avatar";
import VoteFlag from "../components/VoteFlag";
import { TOGGLE_DRAWER } from "@/store/mutation-types";

Vue.use(ConfirmPlugin);

export default {
  name: "Main",
  directives: {
    TransferDom
  },
  components: {
    Scroller,
    XHeader,
    ViewBox,
    Card,
    Sticky,
    Avatar,
    VoteFlag,
    Confirm,
    Spinner
  },
  computed: {
    // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      "submitVoteButtonVisibility"
      // ...
    ]),
    ...mapState({
      voteList: state => state.vote.voteList,
      voteListLoadErr: state => state.vote.voteListLoadErr,
      voteListNoMore: state => state.vote.voteListNoMore
    })
  },
  data() {
    return {
      cordova: Vue.cordova,
      onFetching: true,
      offset: 0
    };
  },
  watch: {
    voteList: {
      deep: true,
      handler: "onVoteListChange"
    },
    voteListLoadErr: {
      deep: true,
      handler: "onVoteListLoadErrChange"
    }
  },
  created() {
    this.refresh();
    const _this = this; // 需要注意 onCancel 和 onConfirm 的 this 指向
    // alert(`Vue : created !`);
    if (typeof window.sessionStorage.bindEvent === "undefined") {
      console.log(`bind deviceready event.`);
      Vue.cordova.on("deviceready", () => {
        // alert(`Cordova : device is ready !`);
        Vue.cordova.on("backbutton", () => {
          // console.log(_this);
          console.log(_this.$route);
          if (_this.$route.name === "Main") {
            // console.log(_this.show);
            // _this.show = true;
            _this.$vux.confirm.show({
              // 组件除show外的属性
              title: "提示",
              content: "退出当前APP？",
              theme: "android",
              onCancel() {},
              onConfirm() {
                window.navigator.app.exitApp();
              }
            });
          } else {
            console.log(_this.$router);
            _this.$router.go(-1);
          }
        });
        window.sessionStorage.bindEvent = true;
      });
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.scroller.reset({ top: 0 });
    });
  },
  methods: {
    ...mapActions(["reqRefreshGetVoteListByPage", "reqGetVoteListByPage"]),
    ...mapMutations([TOGGLE_DRAWER]),
    onAdd() {
      this.$router.push({
        name: "Add"
      });
    },
    go2Content(num) {
      this.$router.push({
        name: "Content",
        params: {
          voteId: num
        }
      });
    },
    onCancel() {
      console.log("on cancel");
    },
    onConfirm() {
      console.log("on confirm");
      window.navigator.app.exitApp();
    },
    onHide() {
      console.log("on hide");
    },
    onShow() {
      console.log("on show");
    },
    onDrawer() {
      this[TOGGLE_DRAWER]();
    },
    onScroll(pos) {
      if (this.onFetching) {
        // do nothing
      } else {
        console.log(`onScroll|`, pos.top);
        if (pos.top < -50) {
          this.refresh();
        }
      }
    },
    onScrollBottom() {
      if (this.onFetching) {
        // do nothing
      } else {
        if (!this.voteListNoMore) {
          console.log(
            `onScrollBottom|`,
            this.onFetching,
            `|hasNoMore|`,
            this.voteListNoMore
          );
          this.onFetching = true;
          this.offset += 10;
          setTimeout(() => {
            this.reqGetVoteListByPage({
              offset: this.offset,
              limit: 10
            });
          }, 1000);
        }
      }
    },
    onVoteListChange() {
      if (this.voteList) {
        this.$nextTick(() => {
          this.$refs.scroller.reset();
        });
        this.onFetching = false;
        console.log(`onVoteListChange|`, this.onFetching);
      }
    },
    onVoteListLoadErrChange() {
      if (this.voteListLoadErr) {
        this.onFetching = false;
        console.log(`onVoteListLoadErrChange|`, this.onFetching);
      }
    },
    refresh() {
      console.log(`needRefresh|`);
      this.onFetching = true;
      this.offset = 0;
      setTimeout(() => {
        this.reqRefreshGetVoteListByPage({
          offset: this.offset,
          limit: 10
        });
      }, 1000);
    }
  }
};
</script>
